# -*- coding: utf-8 -*-
# flake8: noqa

from qiniu import Auth, put_file
import tempfile

# 需要填写你的 Access Key 和 Secret Key
access_key = '51U9lW_W4vmgXbneyXfX9anb8mS2yqU_sI3jYIKn'
secret_key = 'F_mFtLA20EUlibM36Fxwh0IN7_F5eh1trSwVNKSZ'

# 构建鉴权对象
q = Auth(access_key, secret_key)


def upload_qiniu(file_path, file_name):
    # 要上传的空间
    bucket_name = 'p5-didi'
    # 上传后保存的文件名
    key = file_name

    # 如果 file_path 是 InMemoryUploadedFile，保存到临时文件
    if hasattr(file_path, 'read'):
        with tempfile.NamedTemporaryFile(delete=False) as temp_file:
            temp_file.write(file_path.read())
            temp_file_path = temp_file.name
    else:
        temp_file_path = file_path

    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name, key, 3600)
    ret, info = put_file(token, key, temp_file_path)
    print(info)

    # 删除临时文件
    if hasattr(file_path, 'read'):
        import os
        os.remove(temp_file_path)

    return "http://soxgyvna3.hb-bkt.clouddn.com/" + key

# assert ret['key'] == key
# assert ret['hash'] == etag(localfile)
